<?php

namespace app\service;

use app\model\admin\MiniUser;
use app\model\admin\Order;
use app\model\admin\ProfitSet;
use app\model\admin\SysMember;
use app\model\mini\OrderItem;
use app\model\mini\OrderLog;
use Error;
use think\facade\Db;
use EasyWeChat\Factory;




class OrderService
{
    public $payApp;
    public function __construct()
    {
        $miniInfo = config('mini');
        $config = [
            // 必要配置
            'app_id'             => $miniInfo['appid'],
            'mch_id'             => $miniInfo['mch_id'],
            'key'                => $miniInfo['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => app()->getRootPath() . $miniInfo['cert_path'], // XXX: 绝对路径！！！！
            'key_path'           => app()->getRootPath() . $miniInfo['key_path'],      // XXX: 绝对路径！！！！
            'notify_url'         => $miniInfo['callback_url'],     // 你也可以在下单时单独设置来想覆盖它
        ];

        $this->payApp = Factory::payment($config);
    }
    // 订单退款
    public static function refund($order_item_id)
    {
        $service = new OrderService();
        $orderItem = OrderItem::with(['refund'])->find($order_item_id);
        // var_dump($orderItem);
        $order = Order::find($orderItem->order_id);
        $order_id = $order->id;
        // 获取退款金额
        $refundPrice = bcmul(strval($orderItem->goods_price), strval($orderItem->refund_num), 2);
        // 微信退款
        if ($orderItem->old_order_id) {
            // 拆分的订单退款
            $old_order = Order::find($orderItem->old_order_id);
        } else {
            // 全额的退款
            $old_order = Order::find($orderItem->order_id);
        }


        if ($orderItem->spec_type == 1) {
            $refund_desc = '购买' . $orderItem->good_info['goods_name'] . '[' . implode(',', $orderItem->sku['sku']) . ']';
        } else {
            $refund_desc = '购买' . $orderItem->good_info["goods_name"];
        }
        storage_log("old_order:" . json_encode($old_order));
        storage_log("order_item_id:" . $order_item_id);

        // Db::table('user_order_item')->where('id', $order_item_id)->update([
        //     // 'mark' => '',
        //     'refund_status' => 2, //
        //     // 'order_status' => 4,
        //     "updated_at" => time()
        // ]);
        storage_log("退款金额:" . floatval(bcmul($refundPrice, 100, 2)));
        storage_log("订单金额:" . floatval(bcmul($old_order->order_price, 100, 2)));

        $result = $service->payApp->refund->byOutTradeNumber(
            $orderItem->refund->order_sn,
            $orderItem->refund->order_sn . "refund" . rand(1, 100),
            floatval(bcmul($old_order->order_price, 100, 2)),
            floatval(bcmul($refundPrice, 100, 2)),
            [
                // 可在此处传入其他参数，详细参数见微信支付文档
                'refund_desc' => $refund_desc,
            ]
        );
        storage_log("退款返回:" . json_encode($result));

        if ($result['return_code'] == 'SUCCESS') {
            // 微信支付请求成功标记同意退款
            // $isOk = Db::table('user_order_item')->where('id', $order_item_id)->update([
            //     'mark' => '微信退款成功',
            //     'pay_refund_status' => 2,  // 修改为已退款
            //     // 'order_status' => 4,
            //     "updated_at" => time()
            // ]);
            // if (!$isOk) {
            //     OrderLog::create([
            //         "order_id" => $order_id,
            //         "order_item_id" => $order_item_id,
            //         "message" => '数据库修改失败(user_order_item),refund_status=>2'
            //     ]);
            //     return ['result' => false, 'msg' => $result['数据库修改失败(user_order_item)']];
            // }
            if ($result['result_code'] == 'SUCCESS') {
                Db::transaction(function () use ($order_id, $order_item_id, $refundPrice) {
                    storage_log("微信退款成功:order_id=>" . $order_id);
                    Db::table('user_order')->where('id', $order_id)->update([
                        'remark' => '微信退款成功,退款金额:' . $refundPrice,
                        'pay_refund_status' => 2,
                        // 'order_status' => 4, //订单修改为交易关闭 在调用方法前就已修改，因为退款可能会失败，所以该方法只做退钱，不做其他业务
                        "updated_at" => time()
                    ]);
                    // Db::table('user_order_item')->where('id', $order_item_id)->update([
                    //     'mark' => '微信退款成功',
                    //     'refund_status' => 2, //修改为已退款
                    //     // 'order_status' => 4,
                    //     "updated_at" => time()
                    // ]);
                    OrderLog::create([
                        "order_id" => $order_id,
                        "order_item_id" => $order_item_id,
                        "message" => "申请微信退款成功,退款金额：" . $refundPrice
                    ]);
                });
                return ['result' => true, 'msg' => '微信退款成功'];
            } else if ($result['err_code_des']) {
                Db::transaction(function () use ($order_id, $order_item_id, $result, $refundPrice) {
                    Db::table('user_order')->where('id', $order_id)->update([
                        'remark' => '申请退款(' . $refundPrice . ')失败原因:' . $result['err_code_des'],
                        'pay_refund_status' => 3,
                        "updated_at" => time()
                    ]);
                    OrderLog::create([
                        "order_id" => $order_id,
                        "order_item_id" => $order_item_id,
                        "message" => '申请退款(' . $refundPrice . ')失败原因:' . $result['err_code_des']
                    ]);
                });
                // Db::table('user_order_item')->where('id', $order_id)->update([
                //     'remark' => '申请退款失败原因:' . $result['err_code_des'],
                //     'order_status' => -3,
                //     "updated_at" => time()
                // ]);
                return ['result' => false, 'msg' => $result['err_code_des']];
            }
        } else {
            if ($result['return_msg']) {
                $reson = $result['return_msg'];
            } else {
                $reson = '未知错误';
            }
            Db::transaction(function () use ($order_id, $order_item_id, $reson, $refundPrice) {
                Db::table('user_order')->where('id', $order_id)->update([
                    'remark' => '申请退款(' . $refundPrice . ')失败原因:' . $reson,
                    'pay_refund_status' => 3,
                    "updated_at" => time()
                ]);
                OrderLog::create([
                    "order_id" => $order_id,
                    "order_item_id" => $order_item_id,
                    "message" => '申请退款(' . $refundPrice . ')失败原因:' . $reson
                ]);
            });

            return ['result' => false, 'msg' => $reson];
        }
    }
    public static function handleCommission($order_id)
    {
        // var_dump(111);
        Db::transaction(function () use ($order_id) {
            $self = new OrderService();
            $order = Order::with(['orderItem', 'user'])->where([
                'pay_status' => 1,
                // 'order_status' => 5, //交易完成才算收益
                "is_commission" => 0 //
            ])->where('order_status', '<>', 5)->find($order_id);
            storage_log($order_id . '订单不存在或已结算');
            if (!$order) {
                // return error('订单不存在');
                storage_log($order_id . '订单不存在或已结算');
                throw new Error($order_id . '订单不存在或已结算');
            }
            $user = $order->user;
            // 计算运营商利润
            $profit_info = ProfitSet::find(1);
            // 订单金额
            $orderMoney = $order->order_price;
            // 30天内自己刷满1000奖励10元
            $startTime = strtotime($user->created_at);
            $endTime = $startTime + 30 * 24 * 60 * 60;

            storage_log('分佣计算时间:' . $startTime . $endTime);
            // 新用户累计支付2000元
            $newUserPayMoney = Order::where([
                'user_id' => $order->user_id,
                'order_status' => 2,
                'pay_status' => 1,
            ])->sum('order_price');
            storage_log('newUserPayMoney' . $newUserPayMoney);
            // 注册时间内交易满多少元
            $allMoney = Order::where([
                'user_id' => $order->user_id,
                'pay_status' => 1,
                'order_status' => 5, //5是交易成功
            ])->whereBetweenTime('created_at', $startTime, $endTime)->sum('order_price');
            storage_log('allMoney' . $allMoney);
            //注册时间内交易笔数满多少笔
            $allCount = Order::where([
                'user_id' => $order->user_id,
                'pay_status' => 1,
                'order_status' => 5, //5是交易成功
            ])->whereBetweenTime('created_at', $startTime, $endTime)->count();
            storage_log('allCount' . $allCount);

            // 运营商的收益
            $opChangeMoney = $orderMoney * $profit_info->operator_user_profit / 100;
            storage_log("orderMoney" . $orderMoney);
            storage_log("operator_user_profit" . $profit_info->operator_user_profit);
            // storage_log("orderMoney" . $orderMoney);
            // 给运营商分佣
            $operator_info = SysMember::where('id', $user->op_id)->find();
            // 记录运营商的分润

            // $self->recordOpuserBalance($operator_info, $operator_info);
            // 1代理 2普通用户
            if ($user->type == 2) {
                // 
                // 当前用户是商户
                // 获取上级和代理商
                $operator_remark = '商户支付获得收益';
                $agent_leavel = $user->agent_level;
                if ($agent_leavel) {
                    // 三级之内
                    $agent_info = MiniUser::where('id', $user->agent_id)->where('type', 1)->find();
                    switch ($agent_leavel) {
                        case 1:
                            //直属商户
                            $changeMoney = $orderMoney * $profit_info->agent_profit1 / 100;
                            storage_log("orderMoney:" . $orderMoney);
                            storage_log("changeMoney:" . $changeMoney);
                            storage_log("profit_info->agent_profit1:" . $profit_info->agent_profit1);
                            // 拉新用户满2000奖励上级
                            if ($newUserPayMoney >= 2000) {
                                $isHas = Db::table('balance_log')->where([
                                    "user_id" => $agent_info->id,
                                    "from_user_id" => $user->id,
                                    "profit_type" => 4
                                ])->find();
                                if (!$isHas) {
                                    // $totalMoney += $profit_info->new_user_max_money;
                                    $opRemark = "代理商一级商户刷满2000奖励";
                                    $is_ok = Db::table('mini_user')->where('id', $agent_info->id)->inc('balance', $profit_info->new_user_max_money)->update();
                                    if ($is_ok) {
                                        $self->insertBalanceLog($agent_info, $profit_info->new_user_max_money, $order, 0, $opRemark, 4);
                                    }
                                }
                            }
                            // 是否超过5000
                            if ($newUserPayMoney >= 5000) {
                                // 验证是否已经结算
                                $isHas = Db::table('balance_log')->where([
                                    'user_id' => $agent_info->id,
                                    "from_user_id" => $user->id,
                                    "profit_type" => 6
                                ])->find();
                                if ($isHas) {
                                    // 已经结算过
                                    storage_log('代理商:' . $agent_info->id . '已结算直推商户:' . $order->user_id . '刷满5000元奖励');
                                } else {
                                    // 结算佣金
                                    // $totalMoney += $profit_info->agent_get_first_merchant_5000;
                                    $opRemark_5 = "代理商直推商户刷满5000奖励" . $profit_info->agent_get_first_merchant_5000;
                                    $is_ok = Db::table('mini_user')->where('id', $agent_info->id)->inc('balance', $profit_info->agent_get_first_merchant_5000)->update();
                                    if ($is_ok) {
                                        $self->insertBalanceLog($agent_info, $profit_info->agent_get_first_merchant_5000, $order, 0, $opRemark_5, 6);
                                    }
                                }
                            }
                            // 是否超过20000
                            if ($newUserPayMoney >= 20000) {
                                // 验证是否已经结算
                                $isHas_2 = Db::table('balance_log')->where([
                                    'user_id' => $agent_info->id,
                                    "from_user_id" => $user->id,
                                    "profit_type" => 7
                                ])->find();
                                if ($isHas_2) {
                                    // 已经结算过
                                    storage_log('代理商:' . $agent_info->id . '已结算直推商户:' . $order->user_id . '刷满5000元奖励');
                                } else {
                                    // 结算佣金
                                    // $totalMoney += $profit_info->agent_get_first_merchant_20000;
                                    $opRemark_5 = "代理商直推商户刷满20000奖励" . $profit_info->agent_get_first_merchant_20000;
                                    $is_ok = Db::table('mini_user')->where('id', $agent_info->id)->inc('balance', $profit_info->agent_get_first_merchant_20000)->update();
                                    if ($is_ok) {
                                        $self->insertBalanceLog($agent_info, $profit_info->agent_get_first_merchant_20000, $order, 0, $opRemark_5, 7);
                                    }
                                }
                            }
                            // 统一加款：防止多次加款读取余额时还是之前的余额导致加款失败
                            storage_log("直推商户" . $agent_info->id . "支付代理商获得收益，变动金额" . $changeMoney);
                            $is_ok = Db::table('mini_user')->where('id', $agent_info->id)->inc('balance', $changeMoney)->update();
                            $remark = '直推商户支付获得收益';
                            if ($is_ok) {
                                // 记录日志
                                $self->insertBalanceLog($agent_info, $changeMoney, $order, $profit_info->agent_profit1, $remark, 1);
                            }
                            break;
                        case 2:
                            // 上级是商户（代理商的二级用户）
                            $changeMoney = $orderMoney * $profit_info->agent_profit2 / 100;
                            $is_ok = Db::table('mini_user')->where('id', $agent_info->id)->inc('balance', $changeMoney)->update();
                            $remark = '代理商二级商户支付获得收益';
                            if ($is_ok) {
                                // 记录日志
                                $self->insertBalanceLog($agent_info, $changeMoney, $order, $profit_info->agent_profit2, $remark, 1);
                            }

                            // 给商户的上级加款(确定代理商二级用户只能是有一个一级商户)
                            $parent_info = MiniUser::where('id', $user->parent_id)->find();
                            $parentChangeMoney = $orderMoney * $profit_info->merchant_profit1 / 100;
                            $totalMoney = 0;
                            $totalMoney += $parentChangeMoney;

                            // 拉新用户满2000奖励上级
                            // 1todo修改为2000
                            if ($newUserPayMoney >= 2000) {
                                $isHas = Db::table('balance_log')->where([
                                    'user_id' => $parent_info->id,
                                    'from_user_id' => $user->id,
                                    'profit_type' => 4
                                ])->find();
                                if (!$isHas) {
                                    $pChangeRes = Db::table('mini_user')->where('id', $parent_info->id)->inc('balance', $profit_info->new_user_max_money)->update();
                                    if ($pChangeRes) {
                                        $newUserRemark = "直推商户刷满2000奖励" . $profit_info->new_user_max_money;
                                        $self->insertBalanceLog($parent_info, $profit_info->new_user_max_money, $order, 0, $newUserRemark, 4);
                                    }
                                    // 2022/11/26 代理商不存在5元奖励
                                    // 记录上上级奖励（这里上上级实际上是代理商）
                                    // $parentMoney = $profit_info->new_user_max_money2;

                                    // Db::table('mini_user')->where('id', $agent_info->id)->update([
                                    //     "updated_at" => time(),
                                    //     "balance"=>
                                    // ]);

                                    // $pChangeRes = Db::table('mini_user')->where('id', $agent_info->id)->inc('balance', $parentMoney)->update();
                                    // if ($pChangeRes) {
                                    //     $newUserRemark = "间推商户刷满2000奖励" . $profit_info->new_user_max_money2;
                                    //     $self->insertBalanceLog($agent_info, $profit_info->new_user_max_money2, $order, 0, $newUserRemark, 5);
                                    // }

                                }
                            }
                            // 间推商户满5000代理获得收益
                            // 1todo修改为5000
                            if ($newUserPayMoney >= 5000) {
                                $isHas_3 = Db::table("balance_log")->where([
                                    'user_id' => $agent_info->id,
                                    "from_user_id" => $user->id,
                                    "profit_type" => 8
                                ])->find();
                                if (!$isHas_3) {
                                    storage_log("代理商" . $agent_info->id . '间推商户' . $user->id . '刷满5000元奖励' . $profit_info->agent_get_second_merchant_5000);
                                    // 增加余额
                                    $pChangeRes = Db::table('mini_user')->where('id', $agent_info->id)->inc('balance', $profit_info->agent_get_second_merchant_5000)->update();
                                    if ($pChangeRes) {
                                        $newUserRemark_2 = "间推商户刷满5000奖励" . $profit_info->agent_get_second_merchant_5000;
                                        $self->insertBalanceLog($agent_info, $profit_info->agent_get_second_merchant_5000, $order, 0, $newUserRemark_2, 8);
                                    }
                                }
                            }
                            $is_ok = Db::table('mini_user')->where([
                                "id" => $parent_info->id,
                            ])->inc('balance', $parentChangeMoney)->update();
                            $parentRemark = "直推商户支付收益";
                            if ($is_ok) {
                                $self->insertBalanceLog($parent_info, $parentChangeMoney, $order, $profit_info->merchant_profit1, $parentRemark, 1);
                            }
                            break;
                        case 3:
                            // 上级是商户（代理商的三级用户）
                            $changeMoney = $orderMoney * $profit_info->agent_profit2 / 100;
                            $is_ok = Db::table('mini_user')->where([
                                "id" => $agent_info->id,
                            ])->inc('balance', $changeMoney)->update();
                            // 记录日志
                            $remark = '代理商三级商户支付获得收益';
                            if ($is_ok) {
                                $self->insertBalanceLog($agent_info, $changeMoney, $order, $profit_info->agent_profit2, $remark, 1);
                            }
                            // 给商户的上级加款(确定代理商三级用户有两级商户)
                            $parent_info = MiniUser::where('id', $user->parent_id)->find();
                            $parentChangeMoney = $orderMoney * $profit_info->merchant_profit1 / 100;
                            $totalMoney = 0;
                            $totalMoney += $parentChangeMoney;
                            // 拉新用户满2000奖励上级  // 1todo 代理商三级用户满2000元
                            // 1todo 修改为2000
                            if ($newUserPayMoney >= 2000) {
                                $isHas = Db::table('balance_log')->where([
                                    "user_id" => $parent_info->id,
                                    "from_user_id" => $user->id,
                                    "profit_type" => 4
                                ])->find();
                                if (!$isHas) {
                                    $res = Db::table('mini_user')->where('id', $parent_info->id)->inc('balance', $profit_info->new_user_max_money)->update();
                                    if ($res) {
                                        // $totalMoney  += $profit_info->new_user_max_money;
                                        $newUserRemark = "直推商户刷满2000奖励" . $profit_info->new_user_max_money;
                                        $self->insertBalanceLog($parent_info, $profit_info->new_user_max_money, $order, 0, $newUserRemark, 4);
                                    }
                                    // 获取上上级商户
                                    $pPuser = MiniUser::find($parent_info->parent_id);
                                    $pChangeRes = Db::table('mini_user')->where([
                                        "id" => $pPuser->id,
                                    ])->inc('balance', $profit_info->new_user_max_money2)->update();
                                    if ($pChangeRes) {
                                        $newUserRemark = "间推商户刷满2000奖励" . $profit_info->new_user_max_money2;
                                        $self->insertBalanceLog($pPuser, $profit_info->new_user_max_money2, $order, 0, $newUserRemark, 5);
                                    }
                                }
                            }
                            $res = Db::table('mini_user')->where([
                                "id" => $parent_info->id,
                            ])->inc('balance', $parentChangeMoney)->update();
                            if ($res) {
                                $parentRemark = "直推商户支付收益";
                                $self->insertBalanceLog($parent_info, $parentChangeMoney, $order, $profit_info->merchant_profit1, $parentRemark, 1);
                            }
                            // 给商户的上上级加款(利润百分比款)
                            $p_parent_info = MiniUser::where('id', $parent_info->parent_id)->find();
                            $p_parentChangeMoney = $orderMoney * $profit_info->merchant_profit2 / 100;
                            $res = Db::table('mini_user')->where([
                                "id" => $p_parent_info->id,
                            ])->inc('balance', $p_parentChangeMoney)->update();
                            if ($res) {
                                $p_parentRemark = "间推商户的支付收益";
                                $self->insertBalanceLog($p_parent_info, $p_parentChangeMoney, $order, $profit_info->merchant_profit2, $p_parentRemark, 1);
                            }
                            break;
                        default:
                            storage_log('错误的agent_leavel');
                            # code...
                            break;
                    }
                } else {
                    // 不存在agent_leavel
                    // // 给运营商分佣

                    // 给商户的上级分佣
                    $parent_info = MiniUser::where('id', $user->parent_id)->find();
                    $changeMoney = $orderMoney * $profit_info->merchant_profit1 / 100;
                    $totalMoney = 0;
                    $totalMoney += $changeMoney;
                    if ($parent_info) {
                        // 拉新用户满2000奖励上级  //1todo 用户刷满如何获得收益
                        // 1todo改为2000
                        if ($newUserPayMoney >= 2000) {
                            // // 给商户加款
                            // $changeRes = Db::table('mini_user')->where([
                            //     "id" => $parent_info->id,
                            //     "is_finish_new" => 0,
                            // ])->update([
                            //     // "balance" => $parent_info->balance + $profit_info->new_user_max_money,
                            //     "updated_at" => time(),
                            //     "is_finish_new" => 1,
                            // ]);
                            $isHas = Db::table('balance_log')->where([
                                "user_id" => $parent_info->id,
                                "from_user_id" => $user->id,
                                "profit_type" => 4
                            ])->find();
                            // logger('changeRes' . $changeRes);
                            if (!$isHas) {
                                // 状态存在且修改完成后才累计余额
                                // $totalMoney += $profit_info->new_user_max_money;
                                $res = Db::table('mini_user')->where('id', $parent_info->id)->inc('balance', $profit_info->new_user_max_money)->update();
                                if ($res) {
                                    $newUserRemark = "直推商户刷满2000奖励" . $profit_info->new_user_max_money;
                                    $self->insertBalanceLog($parent_info, $profit_info->new_user_max_money, $order, 0, $newUserRemark, 4);
                                }
                                // 给上上级分佣
                                $p_parent_info = MiniUser::find($parent_info->parent_id);
                                // $pMoney = $profit_info->new_user_max_money2;
                                // 计算间推商户刷满2000奖励
                                $res = Db::table('mini_user')->where('id', $p_parent_info->id)->inc('balance', $profit_info->new_user_max_money2)->update();
                                if ($res) {
                                    $p_parent_info_remark = "间推商户刷满2000奖励" . $profit_info->new_user_max_money2;
                                    $self->insertBalanceLog($p_parent_info, $profit_info->new_user_max_money2, $order, 0, $p_parent_info_remark, 5);
                                }
                            }
                        }
                        // Db::table('mini_user')->where('id', $parent_info->id)->update([
                        //     'balance' => $parent_info->balance + $totalMoney,
                        //     "updated_at" => time()
                        // ]);
                        $res = Db::table('mini_user')->where('id', $parent_info->id)->inc('balance', $changeMoney)->update();
                        if ($res) {
                            $remark = "直推商户的支付收益(利润)";
                            $self->insertBalanceLog($parent_info, $changeMoney, $order, $profit_info->merchant_profit1, $remark, 1);
                        }
                        // 获取间推商户
                        $p_parent_info = MiniUser::where('id', $parent_info->parent_id)->find();
                        if ($p_parent_info) {
                            $p_changeMoney = $orderMoney * $profit_info->merchant_profit2 / 100;
                            // Db::table('mini_user')->where('id', $p_parent_info->id)->update([
                            //     'balance' => $p_parent_info->balance + $p_changeMoney,
                            //     "updated_at" => time()
                            // ]);
                            $res = Db::table('mini_user')->where('id', $p_parent_info->id)->inc('balance', $changeMoney)->update();
                            if ($res) {
                                $p_remark = "二级商户的支付收益";
                                $self->insertBalanceLog($p_parent_info, $p_changeMoney, $order, $profit_info->merchant_profit2, $p_remark, 1);
                            }
                        }
                    }
                }
                // 记录日志
            } else {
                $operator_remark = '代理商支付获得收益';
            }
            // 记录满1000分佣
            if ($user->type == 2) {
                // 商户才参加活动  //取消type==2就是代理商也可以参加活动
                // 1todo 修改为1000
                if ($allMoney >= 1000) {
                    // 给自己加款
                    $isHas = Db::table('balance_log')->where([
                        'user_id' => $user->id,
                        "from_user_id" => $user->id,
                        "profit_type" => 2
                    ])->find();
                    if (!$isHas) {
                        $res = Db::table('mini_user')->where('id', $user->id)->inc('balance', $profit_info->max_money_get_money)->update();
                        if ($res) {
                            // 记录日志
                            $remark = '支付满1000获得收益';
                            $self->insertBalanceLog($user, $profit_info->max_money_get_money, $order, 0, $remark, 2);
                        }
                    }
                }
                // 记录满6笔分佣 
                // 1todo 修改为6
                if ($allCount >= 6) {
                    $isHas = Db::table('balance_log')->where([
                        "user_id" => $user->id,
                        "from_user_id" => $user->id,
                        "profit_type" => 3
                    ])->find();
                    if (!$isHas) {
                        // 加款
                        $res = Db::table('mini_user')->where('id', $user->id)->inc('balance', $profit_info->max_count_get_money)->update();
                        if ($res) {
                            // 记录日志
                            $remark = '支付满6笔获得收益';
                            $self->insertBalanceLog($user, $profit_info->max_count_get_money, $order, 0, $remark, 3);
                        }
                    }
                }
            }
            $res = Db::table('member_user')->where([
                "id" => $operator_info->id,
            ])->inc('balance', $opChangeMoney)->update();
            storage_log('member_user' . $operator_info->id);
            storage_log('res' . $res);
            storage_log('opChangeMoney' . $opChangeMoney);
            if ($res) {
                $self->insertBalanceLog($operator_info, $opChangeMoney, $order, $profit_info->operator_user_profit, $operator_remark, 1, 1);
            }
            // 标记完成分佣
            Db::table('user_order')->where('id', $order_id)->update([
                "is_commission" => 1,
                "updated_at" => time()
            ]);
        });
        return 'ok';
    }
    public function insertBalanceLog($user, $money, Order $orderInfo, $rate = '', $remark = '',  $profit_type = 1, $isOperator = 0)
    {
        $data = [
            "user_id" => $user->id,
            "phone" => $user->mobile,
            "type" => 1,
            "money" => $money,
            "before_money" => $user->balance,
            "order_sn" => $orderInfo->order_sn,
            "remark" => $remark,
            "rate" => $rate,
            "create_by" => $user->id,
            "update_by" => $user->id,
            "created_at" => time(),
            "updated_at" => time(),
            "profit_type" => $profit_type,
            "from_user_id" => $orderInfo->user_id,
            // "from_user_phone" => $orderInfo->user_phone,
            "is_operator" => $isOperator
        ];
        storage_log('data' . json_encode($data));
        if ($data['type'] == 1) {
            // 加款
            $data['after_money'] = $data['before_money'] + $data['money'];
        }
        if ($data['type'] == 2) {
            // 扣款
            $data['after_money'] = $data['before_money'] - $data['money'];
        }
        $res = Db::table('balance_log')->insert($data);
        return $res;
    }
}
